package teshop.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import teshop.dao.ProductDAO;
import teshop.domain.Product;

/**
 * Product DAO JPA implementation
 * Created: 25.02.2009
 * @author Hryhory Lira
 *
 */
@Repository
public class ProductDAOWithJPA implements ProductDAO {
	
	@PersistenceContext
	protected EntityManager entityManager;

	/**
	 * @return the entityManager
	 */
	public EntityManager getEntityManager() {
		return entityManager;
	}

	/**
	 * @param entityManager the entityManager to set
	 */
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Override
	public void delete(Long productId) {
		entityManager.createQuery("DELETE FROM Product p WHERE p.productId=:id").setParameter("id", productId).executeUpdate();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> getCategoryProducts(Long pCategoryId, int pPage, int pNumberOnPage) {
		Query query = entityManager.createQuery("SELECT p FROM Product p WHERE p.category.categoryId=:id");
		query.setParameter("id", pCategoryId);
		query.setFirstResult(pPage * pNumberOnPage);
		query.setMaxResults(pNumberOnPage);
		
		return query.getResultList();
	}

	@Override
	public Product loadById(Long id) {
		return entityManager.find(Product.class, id);
	}

	@Override
	public void persist(Product product) {
		entityManager.persist(product);		
	}

	@Override
	public void update(Product product) {
		entityManager.merge(product);		
	}

}
